import serial
from time import sleep
from utils.config import height_offset


def receive(waittime=0.01):
    gga = None
    try:
        ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
        ser.reset_input_buffer()
        for i in range(20):
            data = ser.readline()
            data = data.decode('GBK')

            if 'GGA' in data:
                resolved = int(data.split(',')[6])
                if resolved in [4, 5]:
                    gga = data
                    continue
            if waittime:
                sleep(waittime)
            if i == 19:
                print('gps warning, out of time')

        elevation_data = float(gga.split(',')[7].strip()) - height_offset
        print(elevation_data)

    except:
        print('gps warning, exception')


if __name__ == '__main__':
    receive()
